package com.bjkcst.baselib.utils;

import android.annotation.SuppressLint;
import android.util.Log;

import com.jakewharton.processphoenix.ProcessPhoenix;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Crashhandler implements Thread.UncaughtExceptionHandler {


    @Override
    public void uncaughtException(Thread t, Throwable e) {
        writeCrashLog(e);
        int xCrashCount = SpUtil.getInt(AppUtils.getApp().getApplicationContext(), "xCrashCount", 0);
        if (xCrashCount < 3) {
            Log.e("Crashhandler", String.format("第 %d 次重启", xCrashCount));
            xCrashCount += 1;
            SpUtil.saveInt(AppUtils.getApp().getApplicationContext(), "xCrashCount", xCrashCount);
            ProcessPhoenix.triggerRebirth(AppUtils.getApp().getApplicationContext());
        } else {
            SpUtil.saveInt(AppUtils.getApp().getApplicationContext(), "xCrashCount", 0);
            Log.e("Crashhandler", "程序重启失败");
        }
    }

    private void writeCrashLog(Throwable e) {
        long timeMillis = System.currentTimeMillis();
        @SuppressLint("SimpleDateFormat") StringBuilder stringBuilder =
                new StringBuilder(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
                        .format(new Date(timeMillis)));
        stringBuilder.append(":\n");
        stringBuilder.append(e.getMessage());
        stringBuilder.append("\n");
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        stringBuilder.append(sw.toString());
        String errorLog = stringBuilder.toString();
        LogUtil.save("error", errorLog);
    }
}
